/*
 *Copyright 2021-2023 NERCIS
 *
 *Licensed under the Apache License, Version 2.0 (the "License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *Unless required by applicable law or agreed to in writing, software
 *distributed under the License is distributed on an "AS IS" BASIS,
 *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *See the License for the specific language governing permissions and
 *limitations under the License.
 */

package cn.ac.nercis.pes.service.project.imported;

import cn.ac.nercis.pes.model.dto.common.Result;
import cn.ac.nercis.pes.model.dto.project.ImportConflictDTO;
import cn.ac.nercis.pes.model.standard.prepare.EvaluationContentSDTO;
import cn.ac.nercis.pes.repository.dal.evaluation.EvaluationContentRepository;
import cn.ac.nercis.pes.repository.model.evaluation.EvaluationContentDO;
import cn.ac.nercis.pes.service.utils.CheckFieldUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 测评内容数据导入服务
 *
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Service
public class EvaluationContentImportService {
    private final EvaluationContentRepository evaluationContentRepository;

    @Autowired
    public EvaluationContentImportService(EvaluationContentRepository evaluationContentRepository) {
        this.evaluationContentRepository = evaluationContentRepository;
    }


    public Result<List<ImportConflictDTO>> checkEvaluationContentData(@NonNull String systemId, List<EvaluationContentSDTO> contents) {
        List<EvaluationContentDO> sourceContents = this.evaluationContentRepository.findAllBySystemId(systemId);
        if (CollectionUtils.isEmpty(sourceContents)) {
            return Result.success();
        }
        List<ImportConflictDTO> conflictData = contents.stream()
                .flatMap(ec -> this.checkEvaluationContentData(ec, sourceContents).stream())
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        return Result.success(conflictData);
    }

    public Result<String> importEvaluationContentData(@NonNull String systemId, List<EvaluationContentSDTO> contents, Boolean cover) {
        List<EvaluationContentDO> sourceContents = this.evaluationContentRepository.findAllBySystemId(systemId);
        Result<String> result = Result.success();
        for (EvaluationContentSDTO content : contents) {
            result = this.importEvaluationContentData(systemId, content, sourceContents, cover);
            if (!result.isSuccess()) {
                break;
            }
        }
        return result;
    }

    private List<ImportConflictDTO> checkEvaluationContentData(@NonNull EvaluationContentSDTO importContent, List<EvaluationContentDO> sourceContents) {
        EvaluationContentDO contentDO = sourceContents.stream()
                .filter(st -> StringUtils.equals(st.getNode().getCode(), importContent.getNode().getCode()))
                .findFirst().orElse(null);
        if (Objects.isNull(contentDO)) {
            return Collections.emptyList();
        }
        return CheckFieldUtils.checkField(contentDO, importContent);
    }

    private Result<String> importEvaluationContentData(String systemId, @NonNull EvaluationContentSDTO importContent, List<EvaluationContentDO> sourceContents, Boolean cover) {
        EvaluationContentDO contentDO = sourceContents.stream()
                .filter(st -> StringUtils.equals(st.getNode().getCode(), importContent.getNode().getCode()))
                .findFirst().orElse(null);
        if (Objects.isNull(contentDO)) {
            return createEvaluationContentData(systemId, importContent,sourceContents);
        } else {
            return modifyEvaluationContentData(contentDO, importContent, cover);
        }
    }

    private Result<String> createEvaluationContentData(String systemId, EvaluationContentSDTO importContent,
                                                       List<EvaluationContentDO> sourceContents) {
        EvaluationContentDO contentDO = EvaluationContentDO.builder()
                .systemId(systemId)
                .node(importContent.getNode())
                .data(importContent.getData())
                .build();
        contentDO.setCreateTime(LocalDateTime.now());
        return Optional.of(contentDO)
                .map(this.evaluationContentRepository::save)
                .map(ec->{
                    sourceContents.add(ec);
                    return Result.success(ec.getId());
                })
                .orElse(Result.failed(String.format("导入%s测评内容数据，创建失败", importContent.getNode().getName())));
    }

    private Result<String> modifyEvaluationContentData(EvaluationContentDO sourceContent, EvaluationContentSDTO importContent, Boolean cover) {
        sourceContent.setData(CheckFieldUtils.applyContent(sourceContent.getData(), importContent.getData(), cover));
        sourceContent.setModifyTime(LocalDateTime.now());
        return Optional.of(sourceContent)
                .map(this.evaluationContentRepository::save)
                .map(EvaluationContentDO::getId)
                .map(Result::success)
                .orElse(Result.failed(String.format("导入%s测评内容数据，修改失败", importContent.getNode().getName())));
    }
}
